// pages/recommend-list.js
var api = require('../../api.js');
var app = getApp();
var is_loading_more = false;
var is_no_more = false;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    depotId:null,//仓库id
    productId:null,//商品id
    show_attr_picker:false,//是否展示选择sku弹窗
    form: {
      number: 1,
    },
    goods_list: [],
    params:{
      pageNum: 1,
      pageSize:20,
      show_no_data_tip: false,
    },
    cart_id_list:'',//商品在购物车里的id列表
    moneyIcon:api.MONEYICON,
    moneyIconOther:api.MONEYICONOTHER,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let self = this;
    let depotId =null;
    if (options && options.depotId){
      depotId = options.depotId
    }
    self.setData({
      depotId: depotId
    });
    self.getGoodsList();
   
    const eventChannel = self.getOpenerEventChannel();
    // 监听acceptDataFromOpenerPage事件，获取上一页面通过eventChannel传送到当前页面的数据
    eventChannel.on('acceptDataFromOpenerPage', function (data) {
      if (data.cart_id_list != undefined) {
        self.setData({
          cart_id_list: data.cart_id_list
        })
      }
    })
  },
  getGoodsList: function () {
    var page = this;
    is_no_more = false;
    // var cat_id = page.data.cat_id || "";
    // var p = page.data.pageSize || 1;
    //wx.showNavigationBarLoading();
    //console.log('page.data.goods_list:'+page.data.sort+','+page.data.sort_type);
    app.request({
      url: api.default.recommend_list,
      method:"post",
      data: {
        // productAttributeCategoryId: cat_id,
        depotId: page.data.depotId,
        pageNum: page.data.params.pageNum,
        pageSize: 15,
      },
      success: function (res) {
        if (res.code == 200) {
          console.log(res.data);
          if (!res.data||res.data.length==0) {
            is_no_more = true;
            return;
          }
          let tempArr = page.data.goods_list;
          if(res.data.length>0){
            tempArr = tempArr.concat(res.data)
          }
          if(res.data.length == 0){
            is_loading_more = true;
          }
          page.setData({
            'params.show_no_data_tip': res.data.length == 0,
            goods_list:tempArr
          });
        }
      },
      complete: function () {
        //wx.hideNavigationBarLoading();
      }
    });
  },
  numberSub: function () {
    var page = this;
    var num = page.data.form.number;
    if (num <= 1)
      return true;
    num--;
    page.setData({
      form: {
        number: num,
      }
    });
  },

  numberAdd: function () {
    var page = this;
    var num = page.data.form.number;
    let max = page.data.maxInputNum;
    let curStock = page.data.stock;
    if (curStock <= 0) {
      wx.showToast({
        title: res.message || "库存不足请重选",
        image: "/images/icon-warning.png",
        duration: 2000
      });
      return;
    }
    console.log(max);
    if (max && max > 0 && num >= max) {
      wx.showToast({
        title: '每人限购' + max + '件',
        icon: "none"
      });
      return
    }
    num++;
    page.setData({
      form: {
        number: num,
      }
    });
  },

  numberBlur: function (e) {
    var page = this;
    var num = e.detail.value;
    num = parseInt(num);
    if (isNaN(num))
      num = 1;
    if (num <= 0)
      num = 1;
    page.setData({
      form: {
        number: num,
      }
    });
  },
  addToCart(event){
    let page = this;
    let productId = event.currentTarget.dataset.productid;
    // this.setData({
    //   productId:productId,
    // })
    app.request({
      url: api.default.goodsDetail + productId,
      success: function (res) {
        if (res.code == 200) {
          let data= res.data;
          let attr_group_list = data.productAttributeDetailValue.productSpecsAttributeList;
            attr_group_list.map((val,index)=>{
              let tempArr = val.attributeValue.split(",");
              val.attributeValue=[];
              tempArr.map((val1,idx)=>{
                val.attributeValue.push({
                  value: val1,
                  checked: false,
                  disabled:true,//默认都不可以选择
                })
              })
            });
            page.setData({
              goods: data,
              attr_group_list: attr_group_list,
              productId:productId,
              stock: data.stock,
            })
          page.depotClick(productId);//这里不显示sku弹窗，等接口返回数据后再展示
        }
      }
    })
  },
  depotClick(event){
    let page = this;
    let depotid = page.data.depotId; 
    let productId = event;
    app.request({
        url: api.default.getDepotDetail+depotid+'/'+productId,
        method: 'get',
        success: function (res) {
            if(res.code ==200){
                let data = res.data && res.data.skuStockList;
                let attr_group = page.data.attr_group_list;
                let sp1List =[], sp2List =[],sp3List =[];
                for(let attr of attr_group){//初始化，全部置为false
                    for(let arrtDetail of attr.attributeValue){
                        arrtDetail.checked = false;
                        arrtDetail.disabled = true;
                    }
                }
                for(const item of data){
                    item.sp1?sp1List.push(item.sp1):'';
                    item.sp2?sp2List.push(item.sp2):'';
                    item.sp3?sp3List.push(item.sp3):"";
                };
                
                sp1List = Array.from(new Set(sp1List));
                sp2List = Array.from(new Set(sp2List));
                sp3List = Array.from(new Set(sp3List));
                // console.log(sp1List);
                // console.log(sp2List);
                // console.log(sp3List);
                if(sp1List.length>0){
                    let attrList = attr_group[0].attributeValue;
                    for(var sp1item of sp1List){
                        for(const item2 of attrList){
                            if(sp1item == item2.value){
                                item2.disabled = false;
                                continue
                            } 
                            // else{
                            //     item2.disabled = true;
                            // }
                        }
                    }
                }
                if(sp2List.length>0){
                    let attrList = attr_group[1].attributeValue;
                    for(const item of sp2List){
                        for(const item2 of attrList){
                            if(item == item2.value){
                                item2.disabled = false;
                                continue
                            }
                            //  else{
                            //     item2.disabled = true;
                            // }
                        }
                    }
                }
                if(sp3List.length>0){
                    let attrList = attr_group[2].attributeValue;
                    for(const item of sp3List){
                        for(const item2 of attrList){
                            if(item == item2.value){
                                item2.disabled = false;
                                continue
                            } 
                            // else{
                            //     item2.disabled = true;
                            // }
                        }
                    }
                }
                page.setData({
                    curDepotId:depotid,
                    show_attr_picker:true,
                    //depotProductDTOS:depotList,
                    attr_group_list:attr_group,
                    // price:page.data.goods.flashPromotionProduct.flashPromotionPrice || page.data.goods.price,//没有选中sku的时候，显示当前商品的价格和库存
                    // stock:page.data.goods.stock,
                    skuCode:null,
                    skuId:null,
                });
                console.log(page.data.attr_group_list)
            }else{
                wx.showModal({
                    title:"提示",
                    content: res.message,
                })
            }
        }
    })
  },
  hideAttrPicker(){
    this.setData({
      show_attr_picker: false,
    })
  },
  attrClick: function (e) {
      var page = this;
      console.log(e);
      
    // var attr_group_id = e.target.dataset.groupId; // skuCode
    // var attr_id = e.target.dataset.id; // goodsid
      var attr_val = e.target.dataset.val; // value
      var attr_title = e.target.dataset.title; // title
      var attr_group_list = page.data.attr_group_list;
      var attr_group ;
      //var spArr=[];
      for (var i in attr_group_list) {
        if (attr_group_list[i].attributeName == attr_title){
          attr_group_list[i].attributeValue.map((val,index)=>{
            if (val.value === attr_val && !val.checked) {
              attr_group_list[i].attributeValue[index].checked= true;
            }else{
              attr_group_list[i].attributeValue[index].checked = false;

            }
          })
              // attr_group_list[i].checked = true;
              // attr_group=attr_group_list[i];
          }
      }
      let tempSpArr=[];
      for(let item of attr_group_list){
          for(let item2 of item.attributeValue){
              item2.checked ==true?tempSpArr.push(item2.value):""
          }
      }
      console.log(tempSpArr);
    console.log(attr_group_list);
    //console.log(page.data.spArr);
    page.data.spArr = tempSpArr;
    if (page.data.spArr.length == attr_group_list.length){
      //let sp1, sp2, sp3;
      page.data.spArr.map((val, index) => {
        if(index ==0){
          page.data.sp1 =val;
        } else if (index == 1){
          page.data.sp2 = val;
        }else{
          page.data.sp3 = val;
        }
      });
      console.log(page.data.sp1, page.data.sp2, page.data.sp3);
      page.setData({
          attr_group_list: attr_group_list,
          sp1: page.data.sp1,
          sp2: page.data.sp2,
          sp3: page.data.sp3,
          // attr_group : attr_group
      });
      app.request({
        url: api.default.getAttrDetail,
        method: 'post',
        data: {
          productId: page.data.productId,
          depotId:page.data.depotId,
          sp1: page.data.sp1,
          sp2: page.data.sp2,
          sp3: page.data.sp3,
        },
        success: function (res) {
        // console.log(res);
          if(res.code ==200){
              if(res.data && res.data.stock > 0){
                let data = res.data;
                let price = data.flashPromotionProduct ? data.flashPromotionProduct.exchangeFlashPromotionPrice : data.exchangePrice;
                let max = data.flashPromotionProduct ? data.flashPromotionProduct.flashPromotionLimit : data.stock
                page.setData({
                  price : price,
                  stock: data.stock,
                  maxInputNum: max,
                  skuCode: data.skuCode,
                  skuId: data.id,
                  // attr_group : attr_group
              });
              }else{
                  page.setData({
                      price : page.data.goods. flashPromotionProduct.flashPromotionPrice|| page.data.goods.price,
                      stock: 0,
                      skuCode: null,
                      skuId: null,
                      // attr_group : attr_group
                  });
                  wx.showToast({
                      title: res.message || "库存不足请重选",
                      image: "/images/icon-warning.png",
                      duration:2000
                  });
              }
              
          }
        }
      })
    }else{
      page.setData({
        attr_group_list: attr_group_list,
      //   price:page.data.goods.price,//没有选中sku的时候，显示当前商品的价格和库存//sku信息置空
      //   stock:page.data.goods.stock,
        skuCode:null,
        skuId:null,
        // attr_group : attr_group
      });
    }
  },
  submitToCart(){
    let page = this;
    console.log(this.data);
    wx.showLoading({
      title: "正在提交",
      mask: true,
    });
    app.request({
      url: api.cart.add_cart,
      method: "POST",
      data: {
        //userid:access_token,
        //id: attr_group.id,
        productDepotId: page.data.curDepotId,
        productCategoryId: page.data.goods.productCategoryId,
        brandId: page.data.goods.brandId,
        productBrand: page.data.goods.brandName,
        sp1: page.data.sp1,
        sp2: page.data.sp2,
        sp3: page.data.sp3,
        quantity: page.data.form.number,
        productSn: page.data.goods.productSn,
        productSkuId: page.data.skuId,
        productSkuCode: page.data.skuCode,
        productId: page.data.goods.id,
        price: page.data.price || page.data.goods.price,//这里如果没有规格,取页面上显示的价格
        productName: page.data.goods.name,
        productPic: page.data.goods.pic
      },
      success: function (res) {
        if(res.code ==200){
          let newItem = res.data;
          let allItem = page.data.cart_id_list + ',' + newItem;
          console.log(allItem);
          const eventChannel = page.getOpenerEventChannel();
          eventChannel.emit('acceptDataFromOpenedPage', { data: allItem,depotId:page.data.curDepotId });
          wx.navigateBack();
        }
      }
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    is_loading_more = false
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var page = this;
    if (is_no_more)
        return;
    page.loadMoreGoodsList();
  },
  loadMoreGoodsList: function () {
    var page = this;
    if (is_loading_more)
        return;
    page.setData({
        show_loading_bar: true,
    });
    
    page.setData({
      'params.pageNum' : page.data.params.pageNum+1
    })
    page.getGoodsList();
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})